//
//  RadioButtonManager.m
//  yilutongxing
//
//  Created by T&J on 2017/7/7.
//  Copyright © 2017年 YZE. All rights reserved.
//

#import "RadioButtonManager.h"

@interface RadioButtonManager ()
{
    NSArray *btnArr;
    NSArray *valueArr;
    
    NSInteger currentIndex;
    
    clickBlock callbackFunc;
}
@end

@implementation RadioButtonManager


- (instancetype)initWithData:(NSArray *)buttons vals:(NSArray *)values OnClick:(clickBlock)block{
    self = [super init];
    if (self) {
        btnArr = buttons;
        valueArr = values;
        
        for (UIButton *btn in btnArr) {
            btn.selected = NO;//初始状态所有置未选中
            [btn addTarget:self action:@selector(OnBtnClicked:) forControlEvents:UIControlEventTouchUpInside];
        }
        
        callbackFunc = block;
    }
    
    return self;
}

-(void)OnBtnClicked:(UIButton*)sender{
    for (int i=0; i<btnArr.count; i++) {
        UIButton *btn = btnArr[i];
        btn.selected = NO;
        if (btn==sender) {
            currentIndex = i;
        }
    }
    sender.selected = YES;
    
    if (callbackFunc) {
        callbackFunc(valueArr[currentIndex]);
    }
}

- (NSString *)getChoosen{
    return (NSString*)valueArr[currentIndex];
}

- (void)setChoosen:(NSString *)val{
    [self deselectAll];
    
    for (int i=0; i<valueArr.count; i++) {
        NSString *atval = valueArr[i];
        if ([atval isEqualToString:val]) {
            currentIndex = i;
            UIButton *btn = btnArr[currentIndex];
            btn.selected = YES;
        }
    }
}

- (void)deselectAll{
    for (UIButton *btn in btnArr) {
        btn.selected = NO;
    }
}

@end
